package demo.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author ：liuyh
 * @description：TODO
 * @date ：2020/6/11 8:32
 */
public class AnnotationParser {
    //解析类的注解
    public static void parseTypeAnnotation() throws ClassNotFoundException {
        Class<?> clazz = Class.forName("demo.annotation.MyCourse");
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            CoureInfoAnnotation coureInfoAnnotation = (CoureInfoAnnotation) annotation;
            System.out.println("课程名："+coureInfoAnnotation.courseName()+"\n"+
                    ",标签："+coureInfoAnnotation.courseTag()+"\n"+
                    ", 简介："+coureInfoAnnotation.courseProfile()+"\n"+
                    ", 序号："+coureInfoAnnotation.courseIndex());
        }
    }

    //解析成员变量上的标签
    public static void parseFieldAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.MyCourse");
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            //判断成员变量中是否有指定注解类型的注解
            boolean annotationPresent = declaredField.isAnnotationPresent(PersonInfoAnnotation.class);
            if (annotationPresent) {
                PersonInfoAnnotation annotation = declaredField.getAnnotation(PersonInfoAnnotation.class);
                System.out.println("名称: "+ annotation.name() +"\n"+
                        "年龄: " + annotation.age() +"\n"+
                        "性别: " + annotation.gender() +"\n"
                );
                for (String language : annotation.languages()) {
                    System.out.println("开发语言: "+language);
                }
            }
        }
    }

    //解析方法上的注解
    public static void parseMethodAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.MyCourse");
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            //判断方法上是否有指定注解类型的注解
            boolean annotationPresent = method.isAnnotationPresent(CoureInfoAnnotation.class);
            if (annotationPresent) {
                CoureInfoAnnotation annotation = method.getAnnotation(CoureInfoAnnotation.class);
                System.out.println("课程名："+annotation.courseName()+"\n"+
                        ", 标签："+annotation.courseTag()+"\n"+
                        ", 简介："+annotation.courseProfile()+"\n"+
                        ", 序号："+annotation.courseIndex());
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
//        parseTypeAnnotation();
//        parseFieldAnnotation();
        parseMethodAnnotation();
    }

}
